package com.lxy.ikunoj.code;

import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * @ClassName CodeTest
 * @Description TODO
 * @Author LXY
 * @Date 2024/1/3 13:31
 * @Version 1.0
 */
@SpringBootTest
public class CodeTest2 {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        CodeTest2.Solution solution = new CodeTest2.Solution();

        int[] numsList1 = {2, 4, 3};
        int[] numsList2 = {5, 6, 4};


        ListNode nums = new ListNode(numsList1[0]);
        ListNode current1 = nums;
        for (int i = 1; i < numsList1.length; i++) {
            current1.next = new ListNode(numsList1[i]);
            current1 = current1.next;
        }

        ListNode target = new ListNode(numsList2[0]);
        ListNode current2 = target;
        for (int i = 1; i < numsList2.length; i++) {
            current2.next = new ListNode(numsList2[i]);
            current2 = current2.next;
        }
        ListNode currentNode = solution.addTwoNumbers(nums, target);
        List<Integer> values = new ArrayList<>();
        while (currentNode != null) {
            values.add(currentNode.val);
            currentNode = currentNode.next;
        }
        int[] result = new int[values.size()];
        for (int i = 0; i < values.size(); i++) {
            result[i] = values.get(i);
        }
        System.out.println(Arrays.toString(result));

    }

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode() {}
     * ListNode(int val) { this.val = val; }
     * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    static class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode head = null, tail = null;
            int carry = 0;

            while (l1 != null || l2 != null) {
                int n1 = l1 != null ? l1.val : 0;
                int n2 = l2 != null ? l2.val : 0;
                int sum = n1 + n2 + carry;
                if (head == null) {
                    head = tail = new ListNode(sum % 10);
                } else {
                    tail.next = new ListNode(sum % 10);
                    tail = tail.next;
                }
                carry = sum / 9;
                if (l1 != null) {
                    l1 = l1.next;
                }
                if (l2 != null) {
                    l2 = l2.next;
                }
            }
            if (carry > 0) {
                tail.next = new ListNode(carry);
            }

            return head;
        }
    }

}
